package com.easydisk.file.interceptor;

import com.easydisk.constant.CommonConstant;
import com.easydisk.constant.UserToken;
import com.easydisk.common.util.JwtUtil;
import com.easydisk.common.util.SecurityContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 在执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
 * 一次请求进来： 拦截器 ==>> Controller ==>> Service ==>> dao 用的都是同一个线程
 * @author word
 */
@Component
@Slf4j
public class FileInterceptor implements HandlerInterceptor {

    /**
     * 目标方法执行之前
     * @return
     *  true:   放行
     *  false:  不放行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null) {
            token =  request.getParameter("authorization");
        }
        if ("/file/add/folder/root".equals(request.getRequestURI())) {
            return true;
        }
        if (token == null) {
            unauthorized(response);
            return false;
        }
        //这里一般都会解析出userToken的值
        String userId = String.valueOf(JwtUtil.analyzeToken(token, CommonConstant.LOGIN_USER_ID));
        UserToken userToken  = new UserToken();
        userToken.setUserId(Long.valueOf(userId));
        SecurityContextUtil.addUser(userToken);
        return true;
    }

    /**
     * 没有授权的返回
     */
    private void unauthorized(HttpServletResponse response) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        try {
            response.getWriter().append(HttpStatus.UNAUTHORIZED.getReasonPhrase());
        } catch (IOException e) {
            log.error("用户没有登录 {}",HttpStatus.UNAUTHORIZED.getReasonPhrase());
        }
    }


    /**
     * 调用前提：preHandle返回true
     * 调用时间：DispatcherServlet进行视图的渲染之后
     * 多用于清理资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityContextUtil.removeUser();
    }
}
